//
//  DervateCityViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/8.
//  Copyright © 2016年 Jack. All rights reserved.
//

//获取微商城市

#import "DervateCityViewController.h"
#import "AFNetworking.h"

#import "HeaderFileForEasyToTesco.h"
//
#import "CityAndCountyStr.h"





@interface DervateCityViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSInteger headerBtntag;
    
    NSString *getCityStr;
    NSString *getCountyStr;
    
    
}

@property (nonatomic, strong)NSMutableArray *CityArray;
@property (nonatomic, strong)NSMutableDictionary *Citydic;
@property (nonatomic, strong)UITableView *DervateTableview;



@end

@implementation DervateCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    headerBtntag = -1;
    self.CityArray = [@[]mutableCopy];
    
    [self addCityTopview];
    
    [self getShopsCityandcountyDatasources];
    
    [self addDervatetableviewUI];
    
    
}

- (void)addCityTopview{
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"微商城市列表";

}


- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addDervatetableviewUI {
    self.DervateTableview =[[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.9) style:UITableViewStylePlain];
    self.DervateTableview.dataSource = self;
    self.DervateTableview.delegate = self;
    self.DervateTableview.rowHeight = 30;
    self.DervateTableview.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.DervateTableview];
    
}


#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (headerBtntag == -1) {
        return 0;
    } else {
        if (headerBtntag == section) {
            return [[self.Citydic objectForKey:[NSString stringWithFormat:@"%@", self.CityArray[section]]] count];
        } else {
            return 0;
        }
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cityCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
        }
    
    cell.textLabel.text = [[self.Citydic objectForKey:[NSString stringWithFormat:@"%@", self.CityArray[indexPath.section]]] objectAtIndex:indexPath.row];
        return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.CityArray.count;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerview = [[UIView alloc] init];
//    headerview.backgroundColor = [UIColor grayColor];
    headerview.userInteractionEnabled = YES;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, 30)];
    titleLabel.text = [NSString stringWithFormat:@"%@", self.CityArray[section]];//self.CityArray[section];
    [headerview addSubview:titleLabel];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, WEITH, 40);
    [button addTarget:self action:@selector(shrinkageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerview addSubview:button];
    button.layer.borderWidth = 1;
    button.tag = 550+section;
    return headerview;
}

- (void)shrinkageBtnClick:(UIButton *)button{
    if ((button.tag-550)==headerBtntag) {
        headerBtntag = -1;
    } else {
    headerBtntag = button.tag-550;
    }
    [self.DervateTableview reloadData];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"%@,,,,,%@", self.CityArray[indexPath.section], [[self.Citydic objectForKey:[NSString stringWithFormat:@"%@", self.CityArray[indexPath.section]]] objectAtIndex:indexPath.row]);
    
   getCityStr = [[self.CityArray[indexPath.section] componentsSeparatedByString:@"市"] firstObject];
    
    getCountyStr = [[self.Citydic objectForKey:[NSString stringWithFormat:@"%@", self.CityArray[indexPath.section]]] objectAtIndex:indexPath.row];
    
    CityAndCountyStr *userEntity = [[CityAndCountyStr alloc] init];
    userEntity.cityName = getCityStr;
    userEntity.CountyName = getCountyStr;
    
    
    //通过委托协议传值
    [self.delegate passValue:userEntity];
   
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}





- (void)getShopsCityandcountyDatasources {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    __weak DervateCityViewController *dervateSelf = self;
    
    [mgr GET:@"http://www.ylgw8.com/AppCity/Getssx" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        dervateSelf.Citydic = [dervateSelf toArrayOrNSDictionary:responseObject];
        
        
        dervateSelf.CityArray = [NSMutableArray arrayWithArray:dervateSelf.Citydic.allKeys];
        
        [dervateSelf.DervateTableview reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@", error);
        NSLog(@"%@", operation);
        
    }];
}
// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
